package com.hspedu.hspliving.commodity.service.impl;

import com.hspedu.hspliving.commodity.entity.AttrEntity;
import com.hspedu.hspliving.commodity.service.AttrService;
import com.hspedu.hspliving.commodity.vo.AttrGroupWithAttrsVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.common.utils.PageUtils;
import com.hspedu.common.utils.Query;

import com.hspedu.hspliving.commodity.dao.AttrgroupDao;
import com.hspedu.hspliving.commodity.entity.AttrgroupEntity;
import com.hspedu.hspliving.commodity.service.AttrgroupService;

import javax.annotation.Resource;


@Service("attrgroupService")
public class AttrgroupServiceImpl extends ServiceImpl<AttrgroupDao, AttrgroupEntity> implements AttrgroupService {
    @Resource
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrgroupEntity> page = this.page(
                new Query<AttrgroupEntity>().getPage(params),
                new QueryWrapper<AttrgroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId) {
        //获取关键字
        String key = (String)params.get("key");

        QueryWrapper<AttrgroupEntity> Wrapper = new QueryWrapper<>();
        //封装查询条件
        if(StringUtils.isNotBlank(key)){
//            Wrapper.eq("id",key).or().like("name",key);
            Wrapper.and((obj) -> {
                obj.eq("id", key).or().like("name", key);
            });
        }
        if(categoryId!=0){
            Wrapper.eq("category_id",categoryId);
        }
        IPage<AttrgroupEntity> page = this.page(
                new Query<AttrgroupEntity>().getPage(params),
                Wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCategoryId(Long categoryId) {
        //获取分类的所有属性组
        List<AttrgroupEntity> attrgroupEntities = this.list(
                new QueryWrapper<AttrgroupEntity>().eq("category_id", categoryId));

        //获取每个组的属性，封装到vo
        List<AttrGroupWithAttrsVo> attrsVos = attrgroupEntities.stream().map(attrgroupEntity -> {
            AttrGroupWithAttrsVo attrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrgroupEntity, attrsVo);

            List<AttrEntity> attrEntities = attrService.getAttrByAttrGroupId(attrsVo.getId());
            attrsVo.setAttrs(attrEntities);
            return attrsVo;
        }).collect(Collectors.toList());

        return attrsVos;
    }
}
